package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.EmployeeBean;
import com.project.bean.InboxBean;
import com.project.bean.MailBean;
import com.project.mapper.IEmployeeMapper;
import com.project.mapper.IInboxMapper;
import com.project.mapper.IMailMapper;
import com.project.service.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class MailServiceImpl implements IMailService {
    @Autowired
    private IEmployeeMapper emMapper;
    @Autowired
    private IMailMapper mailMapper;
    @Autowired
    private IInboxMapper inboxMapper;

    @Override
    public void send(MailBean mail, Integer[] receiverIdArray) {
        mailMapper.insert(mail);
//        List<EmployeeBean> receiverList = emMapper.selectBatchIds(Arrays.asList(receiverIdArray));
        for (int i = 0; i < receiverIdArray.length; i++) {
            InboxBean inboxMail = new InboxBean(mail.getMailId(), receiverIdArray[i]);
            inboxMapper.insert(inboxMail);
        }

    }

    @Override
    public IPage<MailBean> cutByItem(Integer pageNO, Integer senderId,
                                     String subject, LocalDate startDate,
                                     LocalDate endDate) {
        QueryWrapper<MailBean> qw = new QueryWrapper<>();
        qw.eq("fk_senderId", senderId);
        qw.eq("m_status", "有效");
        if (subject != null) {
            qw.like("m_subject", subject);
        }

        if (startDate != null) {
            qw.ge("m_date", startDate);
        }

        if (endDate != null) {
            qw.le("m_date", endDate);
        }

        return mailMapper.selectPage(new Page<>(pageNO, 3), qw);
    }

    /**
     * 按id查询邮件信息
     *
     * @param mailId 邮件id
     * @return 邮件对象
     */
    @Override
    public MailBean findById(Integer mailId) {
        return mailMapper.selectById(mailId);
    }

    /**
     * 按id修改邮件状态
     * 将邮件状态设置为无效
     *
     * @param mailId 邮件id
     */
    @Override
    public void update(Integer mailId) {
        MailBean mail = mailMapper.selectById(mailId);
        mail.setEmStatus("无效");
        mailMapper.updateById(mail);
    }
}
